/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.me.tramdroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;


/**
 *
 * @author Robert Krantz, Magnus Spånggård & Magnus Ebbesson
 */
public class Tramdroid extends Activity
{
    private static final int ALERT_DIALOG_ID = 1;

    private EditText fromInput;
    private EditText toInput;

    private Button requestRoute;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.main);

        fromInput = (EditText) findViewById(R.id.fromInput);
        toInput = (EditText) findViewById(R.id.toInput);

        requestRoute = (Button) findViewById(R.id.requestRoute);

        requestRoute.setOnClickListener(new OnClickListener()
        {
            public void onClick(View arg0) {
                try {
                    //throw new UnsupportedOperationException("Not supported yet.");
                    //showDialog(ALERT_DIALOG_ID);
                /* Get a SAXParser from the SAXPArserFactory. */
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();

                    /* Get the XMLReader of the SAXParser we created. */
                    XMLReader xr = sp.getXMLReader();
                    /* Create a new ContentHandler and apply it to the XML-Reader*/
                    XmlHandler myExampleHandler = new XmlHandler();
                    xr.setContentHandler(myExampleHandler);

                    InputSource url = GetAddressSuggestion("07a92932-2ac5-49ca-b633-6eb5b8666c20", "chalmers", 2);
                    /* Parse the xml-data from our URL. */
                    xr.parse(url);
                    /* Parsing has finished. */


                    /* Our ExampleHandler now provides the parsed data to us. */
                    ParsedDataSet parsedExampleDataSet =
                            myExampleHandler.getParsedData();


                    /* Set the result to be displayed in our GUI. */
                    System.out.println(parsedExampleDataSet.toString());
                } catch(SAXException e) {
                    System.out.println("SAXException");
                } catch(ParserConfigurationException e) {
                    System.out.println("ParserConfigurationException");
                } catch(IOException e) {
                    System.out.println("IOException");
                }

            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        switch(id)
        {
            case ALERT_DIALOG_ID:
                return new AlertDialog.Builder(this)
                        .setTitle("Request route alert")
                        .setMessage("Not supported yet.")
                        .create();
        }
        return null;
    }

    private void onRequestRouteClick()
    {
        // send information to västtrafik
    }

    /**
     *
     * @param ident the developer identifier from vasttrafik.
     * @param stop the stop that you want.
     * @param nrOfResults the number of suggestions.
     * @return an InputStream that can be read by the XMLParser.
     */
    public InputSource GetAddressSuggestion(String ident, String stop, int nrOfResults) {
        HttpClient httpClient = new DefaultHttpClient();
        StringBuilder uriBuilder = new StringBuilder("http://www.vasttrafik.se/External_Services/TravelPlanner.asmx/");
        uriBuilder.append("GetAddressesSuggestions");
        uriBuilder.append("?identifier=" + ident);
        uriBuilder.append("&searchString=" + stop);
        uriBuilder.append("&count=" + nrOfResults);

        System.out.println(uriBuilder.toString());
        HttpGet request = new HttpGet(uriBuilder.toString());
        InputSource is = new InputSource();
        try {
            HttpResponse response = httpClient.execute(request);

            int status = response.getStatusLine().getStatusCode();
            if (status != HttpStatus.SC_OK) {
                ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                response.getEntity().writeTo(ostream);
                Log.e("HTTP CLIENT", ostream.toString());
            } else {
                InputStream content = response.getEntity().getContent();
                is.setByteStream(content);
                content.close(); // this will also close the connection
            }

        } catch (Exception e) {
            System.out.println("Failed to send HTTP GET in GetAddressSuggestion.");
        }

        if (is == null) {
            //TODO: throw exception!
        }
        return is;
    }

}
